<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Entries extends CI_Model
{
    function __construct()
    {
        parent::__construct();
        $this->load->model('Tags');
    }
    
    public function get_one_by_slug($slug)
    {
        $field = 'e.eid,e.slug,e.cdtime,e.mdtime,e.types,e.status,e.order,e.uid,e.titles,e.description,e.texts,u.screenName';
        
        $this->db->select($field);
        $this->db->from('entries e');
        $this->db->join('users u', 'e.uid=u.uid', 'left');
        
        $this->db->where(array('e.slug'=>$slug));
        $entries = $this->db->get()->row_array();
        if($isPicture = $this->get_picture($entries['eid']))
            $entries['pictures'] = $isPicture;
        
        if($isTag = $this->Tags->get_tag_entries_by_eid($entries['eid']))
        {
            foreach($isTag as $tg)
            {
                $tgs[$tg['slug']] = $tg['name']; 
            }
            $entries['tags'] = $tgs;
        }
        return $entries;
    }

    function get_one($id)
    {
        $param['field'] = 'e.eid,e.slug,e.cdtime,e.mdtime,e.types,e.status,e.order,e.uid,e.titles,e.description,e.texts,u.screenName,m.name';
        
        $this->db->select($param['field']);
        $this->db->from('entries e');
        $this->db->join('relationships r', 'r.eid=e.eid', 'left');
        $this->db->join('metas m', 'r.mid=m.mid', 'left');
        $this->db->join('users u', 'e.uid=u.uid', 'left');
        
        $this->db->where(array('e.eid'=>$id));
        //$this->db->or_where(array('e.parentid'=>$id));
        $entries = $this->db->get()->row_array();
        if($isPicture = $this->get_picture($id))
            $entries['pictures'] = $isPicture;
        
        if($isTag = $this->Tags->get_tag_entries_by_eid($id))
        {
            foreach($isTag as $tg)
            {
                $tgs[$tg['slug']] = $tg['name']; 
            }
            $entries['tags'] = implode(',', $tgs);
        }
        
        return $entries;
    }
    
    function get_picture($eid){
        $this->load->model('Files_model');
        $picture = $this->Files_model->get_files($eid);
        $returnPicture = array();
        
        if($picture)
        {
            foreach($picture as $pic){
                preg_match('/uploads(.+)/', $pic['full_path'], $full_path);
                $pictures = array(
                    'file_id' => $pic['photo_id'],
                    'name' => $pic['file_name'],
                    'file_path' => base_url().$full_path[0]
                );
                array_push($returnPicture, $pictures);
            }
        }
        
        return $returnPicture;
    }
    
    function getTopicCount(array $param)
    {
        $this->db->select('e.eid');
        $this->db->from('entries e');
        $this->db->join('relationships r', 'r.eid=e.eid', 'left');
        $this->db->join('metas m', 'r.mid=m.mid', 'left');
        $this->db->join('users u', 'e.uid=u.uid', 'left');
        if(isset($param['where']) && ! empty($param['where']))
        {
            $this->db->where($param['where']);
        }
        if(isset($param['like']) && ! empty($param['like']))
        {
            $this->db->like($param['like']);
        }
        return $this->db->count_all_results();
    }
    
    function getTopic(array $param, $page=0, $limit=20)
    {
        if(!isset($param['field']) || empty($param['field']))
        {
            $param['field'] = 'e.eid,e.slug,e.cdtime,e.mdtime,e.types,e.status,e.order,e.uid,e.titles,e.description,e.texts,m.name,m.color,u.screenName';
        }

        $this->db->select($param['field']);
        $this->db->from('entries e');
        $this->db->join('relationships r', 'r.eid=e.eid', 'left');
        $this->db->join('metas m', 'r.mid=m.mid', 'left');
        $this->db->join('users u', 'e.uid=u.uid', 'left');
        if(isset($param['where']) && ! empty($param['where']))
        {
            $this->db->where($param['where']);
        }
        if(isset($param['like']) && ! empty($param['like']))
        {
            $this->db->like($param['like']);
        }
        if(!isset($param['order']) || empty($param['order']))
        {
            $param['order']='cdtime desc';
        }
        
        $this->db->order_by($param['order']);
        $this->db->limit($limit, $page);
        return $this->db->get()->result_array();
    }

    function getEntries()
    {        
        return $this->db->get('options')->result_array();
    }
    
    function add(array $entries)
    {
        $this->load->helper('common');
        /** 构建插入结构 */
        $insertStruct = array(
            'slug'          =>  empty($entries['slug']) ? NULL : slugName($entries['slug']),
            'cdtime'        =>  time(),
            'mdtime'        =>  time(),
            'types'         =>  empty($entries['types']) ? 'topic' : $entries['types'],
            'status'        =>  empty($entries['status']) ? 'publish' : $entries['status'],
            'order'         =>  empty($entries['order']) ? 0 : intval($entries['order']),
            'uid'           =>  isset($entries['uid']) ? $entries['uid'] : $this->session->userdata('uid'),
            'titles'        =>  empty($entries['titles']) ? NULL : $entries['titles'],
            'description'   =>  empty($entries['description']) ? NULL : $entries['description'],
            'texts'         =>  empty($entries['texts']) ? NULL : $entries['texts'],
        );

        if (!empty($entries['eid']))
        {
            unset($insertStruct['cdtime']);
            $this->db->where('eid', $entries['eid']);
            $insertId = $this->db->update('entries', $insertStruct);
        }
        else
        {
            /** 首先插入部分数据 */
            $this->db->insert('entries', $insertStruct);
            $insertId = $this->db->insert_id();
        }
        
        /** 处理附件 */
        if($insertId > 0 && isset($entries['parent']) && !empty($entries['parent']))
        {
            $this->load->model('Files_model');
            $this->Files_model->add_entries_files($insertId, $entries['parent']);
        }
        
        /** category */
        if($insertId > 0 && !empty($entries['category']))
        {
            $this->Tags->add_entries_category($insertId, $entries['category']);
        }
        
        /** 单独的页面 */
        if($insertId > 0 && !empty($entries['page']))
        {
            $this->Tags->add_entries($insertId, $entries['page'], $entries['page']);
        }
        
        /** auto tag */
        if($insertId > 0 && !empty($entries['autotag']))
        {
            $this->Tags->add_entries($insertId, $entries['autotag']);
        }
        /** keyword */
        if($insertId > 0 && !empty($entries['tag']))
        {
            $this->Tags->add_entries($insertId, $entries['tag']);
        }
        
        /** 更新缩略名 */
        if ($insertId > 0 && empty($entries['slug'])) {
            $this->db->where('eid', $insertId);
            $this->db->update('entries', array('slug'=>$insertId));
        }

        return $insertId;
    }
    
    
    public function deleteTopic($eid)
    {
        //删除tag关联
        $this->load->model('Tags');
        $this->Tags->deleteRelationships($eid);
        
        /** 删除附件 */
        $this->db->delete('entries', array('parentid' => $eid));
        
        //删除Topic
        return $this->db->delete('entries', array('eid' => $eid));
    }
}